﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Xml;

namespace XmlAndTreeView
{
    public partial class TreeView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            XmlDataSource ds = new XmlDataSource();
            ds.DataFile = "catalog.xml";
            if (!Page.IsPostBack)
            {
                treeView.DataSource = ds;
                DataBind();
                for (int i = 0; i < treeView.Nodes.Count; i++)
                {
                    TreeNode node = treeView.Nodes[i];
                    UpdateTreeNodes(node, "/*[" + i + "]");
                }
            }
        }

        private void UpdateTreeNodes(TreeNode node, string xpath)
        {
            node.Value = xpath;
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                TreeNode childNode = node.ChildNodes[i];
                UpdateTreeNodes(childNode, xpath + "/*[" + i+"]");
            }
        }

        protected void treeView_SelectedNodeChanged(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/catalog.xml"));
            string xpath = treeView.SelectedNode.Value;
            Response.Write(doc.SelectSingleNode(xpath).InnerXml);
        }
    }
}